#include "screen.h"
#include "util/screen_util.h"


void Screen::showStartupMessage(const String &msg) {
    ScreenUtil::showStartupMessage(tft, msg);
}

void Screen::displayBlock(WiFiClient &client)
{
    static size_t received = 0;
    static uint8_t tail[3];

    while (client.available() && received < BLOCK_SIZE + 3)
    {
        int read_bytes = client.read(blockBuffer + received, BLOCK_SIZE + 3 - received);
        if (read_bytes > 0)
            received += read_bytes;
    }

    if (received < BLOCK_SIZE + 3)
        return;

    memcpy(tail, blockBuffer + BLOCK_SIZE, 3);
    if (tail[0] != TAIL_BYTE_1 || tail[1] != TAIL_BYTE_2 || tail[2] != TAIL_BYTE_3)
    {
        client.write("error");
        received = 0;
        return;
    }

    if (yPos == 0)
        tft.fillScreen(TFT_BLACK);
    tft.pushImage(0, yPos, WIDTH, BLOCK_LINES, (uint16_t *)blockBuffer);
    yPos += BLOCK_LINES;
    if (yPos >= HEIGHT)
        yPos = 0;

    client.write("ok");
    received = 0;
}